// 指令-拖拽+阻止拖拽
export default {
  // 拖拽
  drag: {
    bind(el, binding) {
      el.onmousedown = (event) => {
        // 算出鼠标相对元素的位置
        const disX = event.clientX - el.offsetLeft
        const disY = event.clientY - el.offsetTop
        // 移动的位置
        let left = 0
        let top = 0
        // 是否移动
        let isMove = false
        // 移动元素
        document.onmousemove = (e) => {
          isMove = true
          // 用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
          left = e.clientX - disX
          top = e.clientY - disY
          // 移动样式
          el.style.position = 'absolute'
          el.style.cursor = 'move'
          el.style.opacity = '0.7'
          el.style.left = `${left}px`
          el.style.top = `${top}px`
        }
        // 移动结束
        document.onmouseup = (e) => {
          // 调用绑定的函数
          if (isMove) {
            binding.value.callback({
              index: binding.value.index,
              left,
              top
            })
          }
          // 清除绑定事件
          document.onmousemove = null
          document.onmouseup = null
          // 清除移动样式
          el.style.position = 'relative'
          el.style.cursor = 'auto'
          el.style.opacity = '1'
          el.style.left = '0'
          el.style.top = '0'
        }
      }
    },
    unbind(el) {
      el.onmousedown = null
      document.onmousemove = null
      document.onmouseup = null
    }
  },
  // 阻止拖拽
  stopdrag: {
    bind(el, binding, vnode) {
      el.onmousedown = (event) => {
        event.stopPropagation()
      }
    },
    unbind(el) {
      el.onmousedown = null
    }
  }
}
